using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;
using CoreLib.Plugins;
using CoreLib.Intersect;
using CoreLib;
using CoreLib.Components;
using System.Windows.Forms;
namespace XNAEditor
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Engine
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        CameraPlugin Camera;
        CoreLib.Mouse mouse;
        Plugin model;
        PluginManager pluginmanager = new PluginManager();
        public static MainForm mainform;
        private Ray cursorRay;
        public static Test test;
        public Game1()
        {
            //graphics = new GraphicsDeviceManager(this);
                mainform = new MainForm();
                mainform.Show();
                DrawSurface = mainform.MainWindowPictureBox.Handle;
                Content.RootDirectory = "Content";
                pluginmanager.GetPluginList<Plugin>(System.AppDomain.CurrentDomain.BaseDirectory+"plugins");
                LoadPluginsToGui();
        }

        private void LoadPluginsToGui()
        {
            foreach (Type plugin in pluginmanager.PluginList)
            {
                Type[] interfaces = plugin.GetInterfaces();
               // Add cameras
                if (interfaces.Contains<Type>(typeof(ICameraPlugins)))
                {
                    Camera = new CameraPlugin(this);
                    Camera = (CameraPlugin)pluginmanager.CreateInstance(plugin.Name);

                    ToolStripButton item = new ToolStripButton();

                    item.DisplayStyle = ToolStripItemDisplayStyle.Image;
                   item.BackgroundImageLayout = ImageLayout.Center;         
                   item.ImageScaling = ToolStripItemImageScaling.None;
                   item.ImageAlign = ContentAlignment.MiddleCenter;
                   item.AutoSize = false;
                   item.Width = 74;
                   item.Height = 74;
                    item.Image = (Image)Camera.PluginImage;
                    item.BackgroundImage = (Bitmap)Image.FromFile(System.Environment.CurrentDirectory + "/plugins/button.png");
                  item.ToolTipText = Camera.PluginName;
                  item.Tag = plugin.Name;
                    Engine.CurrentCamera = Camera;
                    mainform.CameraMenuToolsStrip.Items.Add(item);
                }
                if (interfaces.Contains<Type>(typeof(IDrawablePlugins)))
                {
                  DrawablePlugin  model = (DrawablePlugin)pluginmanager.CreateInstance(plugin.Name);

                  foreach (ToolStripButton toolstripbutton in model.ToolStripButtonList)
                  {


                      toolstripbutton.BackgroundImageLayout = ImageLayout.Center;
                      toolstripbutton.ImageScaling = ToolStripItemImageScaling.None;
                      toolstripbutton.TextAlign = ContentAlignment.BottomLeft;
                      toolstripbutton.AutoSize = false;
                      toolstripbutton.ImageAlign = ContentAlignment.MiddleCenter;
                      toolstripbutton.Width = 74;
                      toolstripbutton.Height = 74;
                      toolstripbutton.BackgroundImage = (Bitmap)Image.FromFile(System.Environment.CurrentDirectory + "/plugins/button.png");
                      mainform.CameraMenuToolsStrip.Items.Add(toolstripbutton);

                  }

                   mainform.CameraMenuToolsStrip.Items.Add(new ToolStripSeparator());
                  foreach (Control control in model.MainMenuControlList)
                  {
                      mainform.MainMenuFlowLayoutPanel.Controls.Add(control);
                  }

                }
            }
        }
        public void AddPluginToScene(string plugintypename)
        {
              foreach (Type plugintype in pluginmanager.PluginList)
                 {
                     Type[] interfaces = plugintype.GetInterfaces();
              
                         if (plugintypename == plugintype.Name)
                         {
                             if (interfaces.Contains<Type>(typeof(IPlugins)))
                             {
                                 Plugin plugin = (Plugin)pluginmanager.CreateInstance(plugintype.Name);
                                 plugin.Create();
                             }
                             if (interfaces.Contains<Type>(typeof(IDrawablePlugins)))
                             {
                                 DrawablePlugin plugin = (DrawablePlugin)pluginmanager.CreateInstance(plugintype.Name);
                                 plugin.Create();
                             }
                             if (interfaces.Contains<Type>(typeof(ICameraPlugins)))
                             {
                                 CameraPlugin plugin = (CameraPlugin)pluginmanager.CreateInstance(plugintype.Name);
                             }
                             
                         }
                 }
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            mouse = new CoreLib.Mouse(this);
            test = new Test(game);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (CoreLib.Mouse.LeftButton==Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                  
            }

            // TODO: Add your update logic here
    
            Engine.CurrentCamera = Camera;
     
            base.Update(gameTime);
        }

        public void MousePick()
        {
            float? distance=1000;
            cursorRay = Engine.Cursor.CalculateCursorRay(CCameraComponent.Projection, Engine.CurrentCamera.View);
   
            foreach (object component in this.Components)
            {
                Type[] interfaces = component.GetType().GetInterfaces();
                if (interfaces.Contains<Type>(typeof(IDrawablePlugins)))
                {
                    DrawablePlugin plugin = (DrawablePlugin)component;
                    if (BoundingSphereRayPick.RayIntersectsModel(plugin,BoundingSphereRayPick.InterSectTypeEnum.BoundingSphere).Distance>0)
                    {
                        distance = BoundingSphereRayPick.RayIntersectsModel(plugin,  BoundingSphereRayPick.InterSectTypeEnum.BoundingSphere).Distance;
                        if (Globals.SelectedObject != plugin)
                        {
                        mainform.PropertiesUserControl.PropertiesFlowLayoutPanel.Controls.Clear();
                        mainform.PropertiesUserControl.AddProperties(plugin);                        
                        Globals.SelectedObject = plugin;
                        }
                        else
                        {
                            //mainform.PropertiesUserControl.UpdateProperties(plugin);        
                        }
                    }
                }
            }

        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

       
    }
}
